package top.v5it.japi.plus.example.jpa.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import top.v5it.japi.plus.core.util.HttpServletUtil;
import top.v5it.japi.plus.log.JapiOperLog;
import top.v5it.japi.plus.support.limit.JapiLimit;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("v1")
public class ExampleMethodController {

    private void buildMessage(HttpServletRequest request) {
        final String queryString = request.getQueryString();
        final String requestURI = request.getRequestURI();
        String fullRequestURI = "";
        String body = "";
        try {

            body = StrUtil.str(IoUtil.readBytes(request.getInputStream(), false), request.getCharacterEncoding());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (StrUtil.isNotEmpty(queryString)) fullRequestURI = requestURI + "?" + queryString;
        final Map<String, Object> queryMap = HttpServletUtil.getQueryMap(request);
        final Map<String, Object> parameterMap = HttpServletUtil.getParameterMap(request);
        queryMap.forEach((k, v) -> parameterMap.remove(k));
        final String paramsStr = HttpUtil.toParams(parameterMap);
        body += URLUtil.decode(paramsStr);


        log.info("request.getRequestURI(): {}", request.getRequestURI());
        log.info("fullRequestURI: {}", fullRequestURI);
        log.info("body: {}", body);
        log.info("request.getQueryString(): {}", request.getQueryString());
        log.info("request.getContentType(): {}", request.getContentType());
        log.info("request.getParameterMap(): {}", parameterMap);

    }

    @JapiLimit
    @JapiOperLog("测试get方法")
    @GetMapping("test-get/{id}")
//    @RequestMapping(method = RequestMethod.GET, path = "test-get/{id}")
    public void testGet(@PathVariable("id") Long id, @RequestParam("name") String name, @RequestBody Map<String, Object> json, HttpServletRequest request) {

        buildMessage(request);

    }

    @PostMapping("test-post/{id}")
    public void testPost(@PathVariable("id") Long id, @RequestParam("name") String name, HttpServletRequest request) {

        buildMessage(request);
    }

    @PutMapping("test-put/{id}")
    public void testPut(@PathVariable("id") Long id, @RequestParam("name") String name, HttpServletRequest request) {

        buildMessage(request);

    }

    @DeleteMapping("test-delete/{id}")
    public void testDelete(@PathVariable("id") Long id, @RequestParam("name") String name, HttpServletRequest request) {

        buildMessage(request);

    }
}
